<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import type { TableColumnData } from '@arco-design/web-vue';
  import TableLayout from '@/layout/table-layout.vue';
  import InnerPage from '@/components/inner-page/index.vue';

  import { usePageTable } from '@/hooks/arco/usePageTable';
  import { queryElderArchives } from '@/api/customerManagement/profile';
  import { queryInstStations } from '@/api/structure-management/station';

  import EditModal from './edit.vue';
  import CustomerDetail from './detail.vue';
  import Devices from './devices.vue';
  // 定义表格列
  const columns: TableColumnData[] = [
    {
      title: '客户ID',
      width: 180,
      dataIndex: 'elderId',
    },
    {
      title: '姓名',
      width: 150,
      dataIndex: 'elderName',
    },
    {
      title: '性别',
      width: 80,
      dataIndex: 'gender',
    },
    {
      title: '年龄',
      width: 80,
      dataIndex: 'age',
    },
    {
      title: '联系电话',
      width: 150,
      dataIndex: 'phoneNo',
    },
    {
      title: '签约状态',
      width: 100,
      dataIndex: 'relationStatus',
    },
    {
      title: '关联站点',
      width: 250,
      dataIndex: 'stationName',
    },
    {
      title: '操作',
      align: 'center' as const,
      dataIndex: 'action',
      slotName: 'action',
      fixed: 'right' as const,
      width: 100,
    },
  ];
  const dataPage = ref({
    page: 1,
    pageSize: 1000,
    total: -1,
    optionList: [] as any[], // 添加类型注解
  });
  // 站点筛选处理
  const processOptionList = (list: any[]) => {
    return list.map((item) => ({
      label: item.name,
      value: item.id,
      ...item,
    }));
  };
  const rateSelect = async () => {
    const res = await queryInstStations(
      dataPage.value.page,
      dataPage.value.pageSize
    );
    if (res?.list?.length) {
      dataPage.value.optionList = processOptionList(res.list || []);
    }
  };

  // 使用 usePageTable 管理列表和搜索
  const pageTable = usePageTable({
    searchForm: {
      state: {
        elderName: '',
        signStatus: '',
        stationId: '',
      },
    },
    table: {
      rowKey: 'elderId',
      apiFun: queryElderArchives,
      columns,
      rowSelection: {
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false,
      },
    },
  });

  // 详情页内嵌显示控制（同员工页面的模式）
  const infoHandler = ref({
    props: {
      elderId: '',
      activeTabKey: 'base-info',
    },
    onBack: () => {
      if (viewState.value === 'device') {
        viewState.value = 'detail';
        infoHandler.value.props.activeTabKey = 'device-info';
      } else {
        infoHandler.value.props.elderId = '';
        pageTable.reload();
      }
    },
  });

  const deviceHandler = ref({
    props: {
      elderId: '',
      modelId: '',
      modelName: '',
    },
  });

  const viewState = ref<'detail' | 'device'>('detail');

  // 查看详情（内页展示）
  const handleLook = (record: any) => {
    console.log('点击查看，record.elderId:', record.elderId);
    infoHandler.value.props.elderId = record.elderId;
    viewState.value = 'detail';
    infoHandler.value.props.activeTabKey = 'base-info';
  };

  // 处理详情组件的update事件，只刷新详情数据
  const handleDetailUpdate = () => {
    // 只有当前详情页显示时，才刷新详情数据
    if (infoHandler.value.props.elderId) {
      // 不刷新整个列表，只让详情组件自行刷新
      // 通过触发详情组件的key变化来强制重新加载
      infoHandler.value.props.elderId = `${infoHandler.value.props.elderId}`;
    }
  };

  const openDevice = (payload: { elderId: string; modelId: string; modelName: string }) => {
    deviceHandler.value.props.elderId = payload.elderId;
    deviceHandler.value.props.modelId = payload.modelId;
    deviceHandler.value.props.modelName = payload.modelName;
    viewState.value = 'device';
  };
  const editHandler = ref({
    // 关键修复：将弹窗的 props 包装为 reactive，保证修改可见性等字段能够触发视图更新
    props: reactive({
      data: {} as any,
      visible: false,
      title: '新增客户',
      type: 'add' as any,
    }),
    showAdd: () => {
      editHandler.value.props.visible = true;
      editHandler.value.props.data = {};
      editHandler.value.props.type = 'add';
      editHandler.value.props.title = '新增客户';
    },
    showEdit: (data: any) => {
      editHandler.value.props.visible = true;
      editHandler.value.props.data = data || {};
      editHandler.value.props.type = 'edit';
      editHandler.value.props.title = '编辑客户';
    },
    onSave: () => {
      editHandler.value.props.visible = false;
      pageTable.reload();
    },
  });
  // 分类级别选项
  const levelOptions = [
    {
      label: '游客',
      value: '1',
    },
    {
      label: '签前体验',
      value: '2',
    },
    {
      label: '已签约',
      value: '3',
    },
    {
      label: '已解约',
      value: '4',
    },
  ];
  onMounted(() => {
    rateSelect();
  });
</script>

<template>
  <div class="flex flex-col m-customer-index">
    <div class="m-customer-raw">
      <TableLayout v-bind="pageTable.bindProps" @create="editHandler.showAdd()">
        <template #searchForm="{ state }">
          <a-form-item
            field="elderName"
            label="姓名"
            :label-col="{ style: { whiteSpace: 'nowrap', width: '80px' } }"
          >
            <a-input
              v-model="state.elderName"
              placeholder="请输入客户姓名"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            field="signStatus"
            label="签约状态"
            :label-col="{ style: { whiteSpace: 'nowrap', width: '80px' } }"
          >
            <a-select v-model="state.signStatus" placeholder="请选择签约状态">
              <a-option
                v-for="item in levelOptions"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </a-select>
          </a-form-item>
          <a-form-item
            field="stationId"
            label="关联站点"
            :label-col="{ style: { whiteSpace: 'nowrap', width: '80px' } }"
          >
            <a-select v-model="state.stationId" placeholder="请选择关联站点">
              <a-option
                v-for="item in dataPage.optionList"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </a-select>
          </a-form-item>
        </template>
        <template #action="{ record }">
          <a-space>
            <a-button size="small" type="text" @click="handleLook(record)">
              查看
            </a-button>
          </a-space>
        </template>
      </TableLayout>
      <!-- 编辑弹窗 -->
      <EditModal
        v-bind="editHandler.props"
        @cancel="editHandler.props.visible = false"
        @save="editHandler.onSave"
        @update="pageTable.reload"
      />
    </div>
    <!-- 右侧详情内页 -->
    <InnerPage
      v-if="infoHandler.props.elderId"
      class="m-customer-detail"
      :navName="viewState === 'device' ? '返回客户设备' : '返回列表'"
      @back="infoHandler.onBack"
    >
      <CustomerDetail
        v-if="viewState === 'detail'"
        v-bind="infoHandler.props"
        @update="handleDetailUpdate"
        @edit="editHandler.showEdit"
        @openDevice="openDevice"
      />
      <Devices v-else v-bind="deviceHandler.props" />
    </InnerPage>
  </div>
</template>

<style scoped lang="less">
  .m-customer-index {
    height: 100%;
    overflow-x: hidden;
    overflow-y: auto;
  }
  .m-customer-detail {
    height: 100%;
  }
</style>
